package com.fsd.admin.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.fsd.core.bean.CheckTree;
import com.fsd.core.bean.Tree;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.EhcacheUtil;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.z_major;
import com.fsd.admin.service.z_majorService;
import com.fsd.admin.dao.z_majorDao;
import com.fsd.admin.entity.A_LoginInfo;
import com.google.gson.Gson;

@Repository("z_majorServiceImpl")
public class z_majorServiceImpl extends MainServiceImpl<z_major, String> implements z_majorService{
    
    private static final Logger log = Logger.getLogger(z_majorServiceImpl.class);
    private String depict = "专业";
    
    @Resource(name = "z_majorDaoImpl")
	public void setBaseDao(z_majorDao z_majorDao) {
		super.setBaseDao(z_majorDao);
	}
	
	@Resource(name = "z_majorDaoImpl")
	private z_majorDao objectDao;

	//b_lxzt  栏目状态
	/**
     * 状态启用
     */
	public static final String lxztqy1 = "b_lxztqy";
	public static final String lxztqy2 = "启用";
	/**
     * 状态停用
     */
	public static final String lxztty1 = "b_lxztty";
	public static final String lxztty2 = "停用";
	
	//栏目根类型
	/**
     * 主栏目
     */
	public static final String lmzt = "FSDMAIN";
	/**
     * 相关栏目
     */
	public static final String lmxg = "FSDRELATE";
	/**
     * Wap栏目
     */
	public static final String lmwap = "FSDMOBILE";
	/**
     * Wap相关栏目
     */
	public static final String lmzwapxg = "FSDMOBRELATE";
	/**
     * 政务栏目
     */
	public static final String lmzw = "FSDGOVERNMENT";

	private static final Lock lock = new ReentrantLock();
	
	/**
	 * 栏目递回创建
	 * @param menu
	 * @param menuList
	 */
	private void getObjectStruct(z_major object, List<z_major> objList){
		for (z_major obj : objList) {
			if(object.getId().equals(obj.getParentid())){
				if (object.getLevelpath() != null && !object.getLevelpath().equals("")){
					int num = Integer.valueOf(object.getLevelpath()) + 1;
					obj.setLevelpath(String.valueOf(num));
				}
				if (object.getColumn3() == null || object.getColumn3().equals("")){
					obj.setColumn3(obj.getTitle());
				}else{
					obj.setColumn3(object.getColumn3() + "->" + obj.getTitle());
				}
				if(!"0".equals(object.getParentid())){
					obj.setObject(object);
				}
				object.getList().add(obj);
				if (!Boolean.valueOf(obj.getIsleaf()))
					this.getObjectStruct(obj, objList);
			}
		}
	}
	/**
	 * 获取栏目结构
	 * @param id
	 * @return
	 */
	public z_major getObjectStructByID(String id, String companyid) throws Exception{
		lock.lock();
		Map<String, z_major> objectMap = null;
		String strKey = Config.MAJORMAP + companyid;
		try {
			if(EhcacheUtil.getInstance().get(strKey) == null){
				List<z_major> allObjectList = objectDao.queryByHql("from z_major t where t.companyid in ('" + companyid + "','0') and t.deleted = '0' order by t.sort asc");
				objectMap = new HashMap<String, z_major>();
				List<z_major> objectList = new ArrayList<z_major>();
				List<z_major> objList = new ArrayList<z_major>();
				for (z_major obj : allObjectList) {
					objectMap.put(obj.getId(), obj);
					if("0".equals(obj.getParentid())){
						obj.setLevelpath("0");
						objList.add(obj);
					}else{
						objectList.add(obj);
					}
				}
				for (z_major obj : objList) {
					this.getObjectStruct(obj, objectList);
				}
				EhcacheUtil.getInstance().put(strKey, objectMap);
			}else{
				objectMap = (Map<String, z_major>)EhcacheUtil.getInstance().get(strKey);
			}
		} finally {
			lock.unlock();
		}
		if (objectMap != null && objectMap.containsKey(id))
			return objectMap.get(id);
		else
			return null;
	}
	
	
	private String checkLeaf(String fid){
		long num = objectDao.getCount("parentid = '"+ fid +"'", "deleted = '0'");
		if (num > 0)
			return "false";
		return "true";
	}
	
	/**
	 * 获取栏目子集
	 * @param fid
	 * @param companyid
	 * @return
	 * @throws Exception
	 */
	public List<z_major> queryObjectListById(String fid, String companyid) throws Exception{
		return objectDao.queryByHql("from z_major a where a.companyid = '"+ companyid +"' and a.parentid = '"+ fid +"' and a.deleted = '0' order by sort asc");
	}
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.asc("sort"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				c.add(Restrictions.eq("parentid", objectMap.get("fid")));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 异步加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTree(String fid, boolean isQuery, A_Employee employee) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		String sql = "select * from z_major where parentid = ? and deleted = ?";
		List<z_major> list = objectDao.queryBySql1(sql, fid, "0");

		if (list != null && list.size() > 0){
			Tree tree = null;
			for (z_major major : list) {
				tree = new Tree();
				tree.setId(major.getId());
				tree.setText(major.getTitle());
				tree.setLeaf(Boolean.valueOf(major.getIsleaf()));
				treelist.add(tree);
			}
		}
		return treelist;
	}
	/**
	 * 异步加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTreeByPopdom(String fid, boolean isQuery, A_Employee employee, Map<String, List<String>> popdomMap) throws Exception{
		if (employee.isIsadmin())
			return this.getAsyncObjectTree(fid, isQuery, employee);
		
		List<String> subjectIds = popdomMap.get(Config.POPEDOMSUBJECT);
		subjectIds.addAll(popdomMap.get(Config.POPEDOMSUBJECTW));
		z_major subject = this.getObjectStructByID(fid, employee.getCompanyid());
		List<Tree> treelist = new ArrayList<Tree>();
		if (subject != null && subject.getList() != null && subject.getList().size() > 0){
			Tree tree = null;
			z_major obj = null;
			boolean flage = false;
			for (Object o : subject.getList()) {
				obj = (z_major)o;
				if (!isQuery && !lxztqy1.equals(obj.getStatuscode()))
					continue;
				flage = false;
				for (String sid : subjectIds) {
					if (obj.getId().equals(sid)){
						flage = true;
						break;
					}
				}
				if (!flage)
					continue;
				tree = new Tree();
				tree.setId(obj.getId());
				tree.setText(obj.getTitle());
				tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
				treelist.add(tree);
			}
		}
		return treelist;
	}
	
	/**
	 * 一次性加载树，根据权限加载
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAllObjectTreeByPopdom(ParametersUtil param, boolean isQuery, A_LoginInfo login) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
//		//不是管理员加载人员所属部门
//		if (!login.getEmployee().isIsadmin()){
//			List<String> branchIds = login.getPopedomMap().get(Config.POPEDOMBRANCH);
//			boolean isBranch = false;
//			for (String id : branchIds) {
//				if (id.equals(login.getEmployee().getBranchid())){
//					isBranch = true;
//					break;
//				}
//			}
//			if (!isBranch){
//				B_subject eSubject = this.get(login.getEmployee().getBranchid());
//				if (eSubject != null){
//					if (lxztqy1.equals(eSubject.getStatuscode()) || isQuery){
//						Tree tree = new Tree();
//						tree.setId(eSubject.getId());
//						tree.setText(eSubject.getTitle());
//						tree.setLeaf(true);
//						treelist.add(tree);
//					}
//				}
//			}
//		}
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			List<String> subjectIds = login.getPopedomMap().get(Config.POPEDOMSUBJECT);
			subjectIds.addAll(login.getPopedomMap().get(Config.POPEDOMSUBJECTW));
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				z_major subject = this.getObjectStructByID(objectMap.get("fid").toString(), login.getEmployee().getCompanyid());
				if (subject != null && subject.getList() != null && subject.getList().size() > 0){
					treelist.addAll(this.getObjectTree(objectMap.get("fid").toString(), subject.getList(), 
							subjectIds, 
							login.getEmployee().isIsadmin(),
							isQuery));
				}
			}
		}
		return treelist;
	}
	private List<Tree> getObjectTree(String fid, List<Object> list, List<String> subjectPop, 
			boolean isAdmin, boolean isQuery) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		Tree node = null;
		z_major obj = null;
		for (Object o : list) {
			obj = (z_major)o;
			if (!isQuery && !lxztqy1.equals(obj.getStatuscode()))
				continue;
			if (isAdmin || subjectPop.indexOf(obj.getId()) != -1){
				if (obj.getParentid().equals(fid)){
					node = new Tree();
					node.setId(obj.getId());
					node.setText(obj.getTitle());
					node.setLeaf(Boolean.valueOf(obj.getIsleaf()));
					if(!node.isLeaf()){
						node.setExpanded(true);
						node.setChildren(this.getObjectTree(obj.getId(), obj.getList(), 
								subjectPop, isAdmin, isQuery));
					}
					treelist.add(node);
				}
			}
		}
		return treelist;
	}
	
	/**
	 * 查询窗口表格显示，根据权限加载
	 * @return
	 * @throws Exception
	 */
	public List<z_major> getAllObjectListByPopdom(ParametersUtil param, boolean isQuery, A_LoginInfo login) throws Exception{
		List<z_major> objList = new ArrayList<z_major>();
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			List<String> subjectIds = login.getPopedomMap().get(Config.POPEDOMSUBJECT);
			subjectIds.addAll(login.getPopedomMap().get(Config.POPEDOMSUBJECTW));
			String txt = "";
			if(objectMap.get("txt") != null && !"".equals(objectMap.get("txt"))){
				txt = objectMap.get("txt").toString();
			}
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				List<String> idList = new ArrayList<String>();
				z_major subject = this.getObjectStructByID(objectMap.get("fid").toString(), login.getEmployee().getCompanyid());
				if (subject != null && subject.getList() != null && subject.getList().size() > 0){
					this.getObjectList(objList, txt, objectMap.get("fid").toString(), subject.getList(), 
							subjectIds,
							idList,
							login.getEmployee().isIsadmin(),
							isQuery);
				}
			}
		}
		return objList;
	}
	private void getObjectList(List<z_major> objList, String txt, String fid, List<Object> list, 
			List<String> subjectPop, List<String> idList, boolean isAdmin, boolean isQuery) throws Exception{
		z_major obj = null;
		for (Object o : list) {
			obj = (z_major)o;
			if (!isQuery && !lxztqy1.equals(obj.getStatuscode()))
				continue;
			if (isAdmin || subjectPop.indexOf(obj.getId()) != -1){
				if (obj.getParentid().equals(fid)){
					if (txt.equals("")){
						objList.add(this.getObjectClone(obj));
					}else{
						if (obj.getTitle().indexOf(txt) != -1){
							this.getObjectListParent(objList, idList, obj);
							idList.add(obj.getId());
							objList.add(this.getObjectClone(obj));
						}
					}
					if(!Boolean.valueOf(obj.getIsleaf())){
						this.getObjectList(objList, txt, obj.getId(), obj.getList(), 
								subjectPop, idList, isAdmin, isQuery);
					}
				}
			}
		}
	}
	private void getObjectListParent(List<z_major> objList, List<String> idList, z_major obj){
		if (obj.getObject() != null){
			if (!idList.contains(((z_major)obj.getObject()).getId())){
				this.getObjectListParent(objList, idList, (z_major)obj.getObject());
				idList.add(((z_major)obj.getObject()).getId());
				objList.add(this.getObjectClone((z_major)obj.getObject()));
			}
		}
	}
	/**
	 * 克隆对象
	 * @param object
	 * @return
	 */
	private z_major getObjectClone(z_major object){
		z_major newObj = new z_major();
		newObj.setId(object.getId());
		newObj.setParentid(object.getParentid());
		newObj.setParentname(object.getParentname());
		newObj.setTitle(object.getTitle());
		newObj.setDescribes(object.getDescribes());
		newObj.setSubjectid(object.getSubjectid());
		newObj.setSubjectname(object.getSubjectname());
		newObj.setImageurl1(object.getImageurl1());
		newObj.setImageurl2(object.getImageurl2());
		newObj.setSort(object.getSort());
		newObj.setIsaurl(object.getIsaurl());
		newObj.setAurl(object.getAurl());
		newObj.setIssingle(object.getIssingle());
		newObj.setSinglearticleid(object.getSinglearticleid());
		newObj.setIspublish(object.getIspublish());
		newObj.setRemark(object.getRemark());
		newObj.setLevelpath(object.getLevelpath());
		newObj.setCompanyid(object.getCompanyid());
		newObj.setIsleaf(object.getIsleaf());
		newObj.setColumn1(object.getColumn1());
		newObj.setColumn2(object.getColumn2());
		newObj.setColumn3(object.getColumn3());
		newObj.setAdddate(object.getAdddate());
		newObj.setAddemployeeid(object.getAddemployeeid());
		newObj.setAddemployeename(object.getAddemployeename());
		newObj.setUpdatedate(object.getUpdatedate());
		newObj.setUpdateemployeeid(object.getUpdateemployeeid());
		newObj.setUpdateemployeename(object.getUpdateemployeename());
		newObj.setStatuscode(object.getStatuscode());
		newObj.setStatusname(object.getStatusname());
		newObj.setDeleted(object.getDeleted());
		return newObj;
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param obj
	 */
	public void saveObject(z_major obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
        	if (obj.getId() == obj.getParentid()){
    			throw new BusinessException(depict + "所属栏目不得选择自己!");
        	}
        	z_major obj_old = objectDao.get(obj.getId());
			String fid = obj_old.getParentid();
			obj_old.setParentid(obj.getParentid());
			obj_old.setParentname(obj.getParentname());
			obj_old.setTitle(obj.getTitle());
			obj_old.setDescribes(obj.getDescribes());
			obj_old.setSubjectid(obj.getSubjectid());
			obj_old.setSubjectname(obj.getSubjectname());
			obj_old.setImageurl1(obj.getImageurl1());
			obj_old.setImageurl2(obj.getImageurl2());
			obj_old.setSort(obj.getSort());
			obj_old.setIsaurl(obj.getIsaurl());
			obj_old.setAurl(obj.getAurl());
			obj_old.setIssingle(obj.getIssingle());
			obj_old.setSinglearticleid(obj.getSinglearticleid());
			obj_old.setIspublish(obj.getIspublish());
			obj_old.setColumn2(obj.getColumn2());
			obj_old.setRemark(obj.getRemark());
			obj_old.setUpdatedate(this.getData());//设置修改日期
			obj_old.setUpdateemployeeid(employee.getId());//设置修改用户id
			obj_old.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
			obj_old.setStatuscode(lxztty1);
			obj_old.setStatusname(lxztty2);
			objectDao.update(obj_old);
			if (!fid.equals(obj.getParentid())){
				objectDao.executeHql("update z_major t set t.isleaf = '" + this.checkLeaf(obj.getParentid()) + "' where t.id = '" + obj.getParentid() + "'");
				objectDao.executeHql("update z_major t set t.isleaf = '" + this.checkLeaf(fid) + "' where t.id = '" + fid + "'");
			}
		}else{
			//添加
			obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			obj.setIsleaf("true");
			obj.setDeleted("0");//设置删除标志(0:正常 1：已删除)
			obj.setStatuscode(lxztty1);
			obj.setStatusname(lxztty2);
			objectDao.save(obj);
			objectDao.executeHql("update z_major t set t.isleaf = 'false' where t.id = '" + obj.getParentid() + "'");
		}
		EhcacheUtil.getInstance().remove(Config.MAJORMAP + employee.getCompanyid());
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getTitle(), employee, z_majorServiceImpl.class);
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public z_major getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		z_major obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 */
	public void delObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String oid = dir.get(0);
		objectDao.executeHql("update z_major t set t.deleted = '1' where t.id in (" + ids + ")");
		z_major obj = objectDao.get(oid);
		if (obj != null){
			objectDao.executeHql("update z_major t set t.isleaf = '" + this.checkLeaf(obj.getParentid()) + "' where t.id = '" + obj.getParentid() + "'");
		}
		EhcacheUtil.getInstance().remove(Config.MAJORMAP + obj.getCompanyid());
	}
	
	/**
	 * 顺序排序
	 * @param parameters
	 */
	public void updateSortObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		List<String> idList = (List<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(idList);
		z_major objDW = objectDao.get(objectMap.get("id").toString());
		if (objDW == null)
			throw new BusinessException(depict + "获取定位对象为空!");
		List<z_major> objList = objectDao.queryByHql("from z_major t where " +
				"t.parentid = '" + objDW.getParentid() + "' and t.deleted = '0' " +
				"and t.id not in (" + ids + ") " +
				"and t.sort >= " + objDW.getSort() + " order by t.sort asc");
		long sort = objDW.getSort();
		for (String id : idList) {
			objectDao.executeHql("update z_major t set t.sort = " + sort + " where t.id = '" + id + "'");
			sort++;
		}
		for (z_major obj : objList) {
			objectDao.executeHql("update B_subject t set t.sort = " + sort + " where t.id = '" + obj.getId() + "'");
			sort++;
		}
		EhcacheUtil.getInstance().remove(Config.MAJORMAP + objDW.getCompanyid());
	}

	
	/**
	 * 获取权限树
	 * @param user
	 * @return
	 */
	public List<CheckTree> getAllQxObjectCheck(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}

		List<CheckTree> menulist = new ArrayList<CheckTree>();
		z_major subject = this.getObjectStructByID(
				objectMap.get("id").toString(), employee.getCompanyid());
		if (subject == null)
			return menulist;
		List<Object> list = subject.getList();
		if (list == null || list.size() == 0)
			return menulist;
		CheckTree tree = null;
		z_major obj = null;
		for (Object object : list) {
			obj = (z_major) object;
			if (!lxztqy1.equals(obj.getStatuscode()))
				continue;
			tree = new CheckTree();
			tree.setChecked(false);
			tree.setId(obj.getId());
			tree.setText(obj.getTitle());
			tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			this.getCheckTreeStruct(tree, obj.getList());
			menulist.add(tree);
		}
		return menulist;
	}
	/**
	 * 获得复选框权限结构
	 * @param isAdmin
	 * @param fTree
	 * @param list
	 */
	private void getCheckTreeStruct(CheckTree fTree, List<Object> list){
		fTree.setLeaf(true);
		if (list == null && list.size() == 0){
			return;
		}
		CheckTree tree = null;
		z_major obj = null;
		for (Object object : list) {
			obj = (z_major) object;
			if (!lxztqy1.equals(obj.getStatuscode()))
				continue;
			fTree.setLeaf(false);
			fTree.setExpanded(true);
			tree = new CheckTree();
			tree.setChecked(false);
			tree.setId(obj.getId());
			tree.setText(obj.getTitle());
			tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			this.getCheckTreeStruct(tree , obj.getList());
			fTree.getChildren().add(tree);
		}
	}
	
	/**
	 * 获取权限树
	 * @param user
	 * @return
	 */
	public List<CheckTree> getQxObjectCheck(ParametersUtil parameters, A_Employee employee, 
			Map<String, List<String>> popdomMap) throws Exception{
		if (employee.isIsadmin())
			return this.getAllQxObjectCheck(parameters, employee);
		
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		
		List<String> subjectIds = popdomMap.get(Config.POPEDOMSUBJECT);
		subjectIds.addAll(popdomMap.get(Config.POPEDOMSUBJECTW));
		
		List<CheckTree> menulist = new ArrayList<CheckTree>();
		z_major obj = this.getObjectStructByID(
				objectMap.get("id").toString(), employee.getCompanyid());
		if (obj == null)
			return menulist;
		List<Object> list = obj.getList();
		if (list == null || list.size() == 0)
			return menulist;
		menulist = this.getCheckTreeStruct(list, subjectIds);
		return menulist;
	}
	/**
	 * 获得复选框权限结构
	 * @param isAdmin
	 * @param fTree
	 * @param list
	 */
	private List<CheckTree> getCheckTreeStruct(List<Object> list, List<String> popdomList){
		List<CheckTree> treeList = new ArrayList<CheckTree>();
		if (list == null && list.size() == 0){
			return treeList;
		}
		CheckTree tree = null;
		z_major obj = null;
		boolean flage = false;
		List<CheckTree> children = null;
		for (Object object : list) {
			obj = (z_major) object;
			if (!lxztqy1.equals(obj.getStatuscode()))
				continue;
			flage = false;
			for (String pid : popdomList) {
				if (obj.getId().equals(pid)){
					flage = true;
					break;
				}
			}
			if (!flage)
				continue;
			tree = new CheckTree();
			tree.setChecked(false);
			tree.setId(obj.getId());
			tree.setText(obj.getTitle());
			tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			children = this.getCheckTreeStruct(obj.getList(), popdomList);
			if (children.size() == 0)
				tree.setLeaf(true);
			else{
				tree.setLeaf(false);
				tree.setExpanded(true);
				for (CheckTree checkTree : children) {
					tree.getChildren().add(checkTree);
				}
			}
			treeList.add(tree);
		}
		return treeList;
	}
	
	private static String sqlSubject = "select s.title as NAME, " + 
			"(select count(*) from z_major r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0101000000' " + 
			"and r.adddate <= '@#$%0131235959') as ONE, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0201000000' " + 
			"and r.adddate < '@#$%0301000000') as TWO, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0301000000' " + 
			"and r.adddate <= '@#$%0331235959') as THREE, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0401000000' " + 
			"and r.adddate <= '@#$%0430235959') as FOUR, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0501000000' " + 
			"and r.adddate <= '@#$%0531235959') as FIVE, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0601000000' " + 
			"and r.adddate <= '@#$%0630235959') as SIX, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0701000000' " + 
			"and r.adddate <= '@#$%0731235959') as SEVEN, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0801000000' " + 
			"and r.adddate <= '@#$%0831235959') as EIGHT, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0901000000' " + 
			"and r.adddate <= '@#$%0930235959') as NINE, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%1001000000' " + 
			"and r.adddate <= '@#$%1031235959') as TEN, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%1101000000' " + 
			"and r.adddate <= '@#$%1130235959') as ELEVEN, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%1201000000' " + 
			"and r.adddate <= '@#$%1231235959') as TWELVE, " + 
			"(select count(*) from B_article r,B_subject t  " + 
			"where r.subjectid = t.id and t.id = s.id  " + 
			"and r.adddate >= '@#$%0101000000' " + 
			"and r.adddate <= '@#$%1231235959') as SUMMATION " + 
			"from B_subject s where s.id='%$#@' ";
	/**
	 * 根据查询条件加载统计数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public List<Object> getObjectStat(ParametersUtil param, A_Employee employee) throws Exception{
		List<Object> statList = new ArrayList<Object>();
		String year = "";
		String subid = "";
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		year = objectMap.get("year").toString();
		subid = objectMap.get("subject").toString();
		if (year.equals("") || subid.equals("")){
			return statList;
		}
		z_major subject = this.getObjectStructByID(subid, employee.getCompanyid());
		if (subject.getId().equals("FSDMAIN")){
			this.getObjectStatChild(statList, subject.getList(), year, 0);
		}else{
			List<Object> rowList = new ArrayList<Object>();
			rowList.add(subject);
			this.getObjectStatChild(statList, rowList, year, 0);
		}
		Map<String, Object> sList = null;
		int one = 0;
		int two = 0;
		int three = 0;
		int four = 0;
		int five = 0;
		int six = 0;
		int seven = 0;
		int eight = 0;
		int nine = 0;
		int ten = 0;
		int eleven = 0;
		int twelve = 0;
		int summation = 0;
		for (Object obj : statList) {
			sList = (Map<String, Object>)obj;
			one += Integer.valueOf(sList.get("one").toString());
			two += Integer.valueOf(sList.get("two").toString());
			three += Integer.valueOf(sList.get("three").toString());
			four += Integer.valueOf(sList.get("four").toString());
			five += Integer.valueOf(sList.get("five").toString());
			six += Integer.valueOf(sList.get("six").toString());
			seven += Integer.valueOf(sList.get("seven").toString());
			eight += Integer.valueOf(sList.get("eight").toString());
			nine += Integer.valueOf(sList.get("nine").toString());
			ten += Integer.valueOf(sList.get("ten").toString());
			eleven += Integer.valueOf(sList.get("eleven").toString());
			twelve += Integer.valueOf(sList.get("twelve").toString());
			summation += Integer.valueOf(sList.get("summation").toString());
		}
		sList = new HashMap<String, Object>();
		sList.put("name", "月累计");
		sList.put("one", one);
		sList.put("two", two);
		sList.put("three", three);
		sList.put("four", four);
		sList.put("five", five);
		sList.put("six", six);
		sList.put("seven", seven);
		sList.put("eight", eight);
		sList.put("nine", nine);
		sList.put("ten", ten);
		sList.put("eleven", eleven);
		sList.put("twelve", twelve);
		sList.put("summation", summation);
		statList.add(sList);
		return statList;
	}
	private void getObjectStatChild(List<Object> statList, List<Object> rowList, String year, int num){
		z_major subject = null;
		String sql = "";
		String sp = "";
		for (int i = 0; i < num; i++) {
			sp += "　";
		}
		if (!sp.equals("")){
			sp += "|-";
		}
		List<Object> valueList = null;
		Map vList = null;
		Map<String, Object> sList = null;
		for (int i = 0; i < rowList.size(); i++) {
			subject = (z_major)rowList.get(i);
			sql = this.sqlSubject.replace("@#$%", year);
			sql = sql.replace("%$#@", subject.getId());
			valueList = objectDao.queryBySql(sql);
			vList = (Map)valueList.get(0);
			sList = new HashMap<String, Object>();
			sList.put("id", subject.getId());
			sList.put("name", sp + vList.get("NAME").toString());
			sList.put("one", vList.get("ONE").toString());
			sList.put("two", vList.get("TWO").toString());
			sList.put("three", vList.get("THREE").toString());
			sList.put("four", vList.get("FOUR").toString());
			sList.put("five", vList.get("FIVE").toString());
			sList.put("six", vList.get("SIX").toString());
			sList.put("seven", vList.get("SEVEN").toString());
			sList.put("eight", vList.get("EIGHT").toString());
			sList.put("nine", vList.get("NINE").toString());
			sList.put("ten", vList.get("TEN").toString());
			sList.put("eleven", vList.get("ELEVEN").toString());
			sList.put("twelve", vList.get("TWELVE").toString());
			sList.put("summation", vList.get("SUMMATION").toString());
			statList.add(sList);
			if (subject.getList() != null && subject.getList().size() > 0){
				this.getObjectStatChild(statList, subject.getList(), year, num + 1);
			}
		}
	}
	
	/**
	 * 加载下载数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public List<Object> getDownloadData(ParametersUtil param, A_Employee employee) throws Exception{
		List<Object> statList = new ArrayList<Object>();
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		String year = objectMap.get("year").toString();
		String subid = objectMap.get("subject").toString();
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		if(dir.size() > 0 ){
			for(int i = 0; i < dir.size(); i++){
				z_major subject = this.getObjectStructByID(dir.get(i), employee.getCompanyid());
				if (subject == null){
					continue;
				}
				List<Object> rowList = new ArrayList<Object>();
				rowList.add(subject);
				this.getDownloadDataChild(statList, rowList, year, 0, false);
			}
		}else{
			z_major subject = this.getObjectStructByID(subid, employee.getCompanyid());
			this.getDownloadDataChild(statList, subject.getList(), year, 0, true);
		}
		
		Map<String, Object> sList = null;
		int one = 0;
		int two = 0;
		int three = 0;
		int four = 0;
		int five = 0;
		int six = 0;
		int seven = 0;
		int eight = 0;
		int nine = 0;
		int ten = 0;
		int eleven = 0;
		int twelve = 0;
		int summation = 0;
		for (Object obj : statList) {
			sList = (Map<String, Object>)obj;
			one += Integer.valueOf(sList.get("one").toString());
			two += Integer.valueOf(sList.get("two").toString());
			three += Integer.valueOf(sList.get("three").toString());
			four += Integer.valueOf(sList.get("four").toString());
			five += Integer.valueOf(sList.get("five").toString());
			six += Integer.valueOf(sList.get("six").toString());
			seven += Integer.valueOf(sList.get("seven").toString());
			eight += Integer.valueOf(sList.get("eight").toString());
			nine += Integer.valueOf(sList.get("nine").toString());
			ten += Integer.valueOf(sList.get("ten").toString());
			eleven += Integer.valueOf(sList.get("eleven").toString());
			twelve += Integer.valueOf(sList.get("twelve").toString());
			summation += Integer.valueOf(sList.get("summation").toString());
		}
		sList = new HashMap<String, Object>();
		sList.put("name", "月累计");
		sList.put("one", one);
		sList.put("two", two);
		sList.put("three", three);
		sList.put("four", four);
		sList.put("five", five);
		sList.put("six", six);
		sList.put("seven", seven);
		sList.put("eight", eight);
		sList.put("nine", nine);
		sList.put("ten", ten);
		sList.put("eleven", eleven);
		sList.put("twelve", twelve);
		sList.put("summation", summation);
		statList.add(sList);
		return statList;
	}
	private void getDownloadDataChild(List<Object> statList, List<Object> rowList, 
			String year, int num, boolean isChild){
		z_major subject = null;
		String sql = "";
		String sp = "";
		for (int i = 0; i < num; i++) {
			sp += "　";
		}
		if (!sp.equals("")){
			sp += "|-";
		}
		List<Object> valueList = null;
		Map vList = null;
		Map<String, Object> sList = null;
		for (int i = 0; i < rowList.size(); i++) {
			subject = (z_major)rowList.get(i);
			sql = this.sqlSubject.replace("@#$%", year);
			sql = sql.replace("%$#@", subject.getId());
			valueList = objectDao.queryBySql(sql);
			vList = (Map)valueList.get(0);
			sList = new HashMap<String, Object>();
			sList.put("name", sp + vList.get("NAME").toString());
			sList.put("one", vList.get("ONE").toString());
			sList.put("two", vList.get("TWO").toString());
			sList.put("three", vList.get("THREE").toString());
			sList.put("four", vList.get("FOUR").toString());
			sList.put("five", vList.get("FIVE").toString());
			sList.put("six", vList.get("SIX").toString());
			sList.put("seven", vList.get("SEVEN").toString());
			sList.put("eight", vList.get("EIGHT").toString());
			sList.put("nine", vList.get("NINE").toString());
			sList.put("ten", vList.get("TEN").toString());
			sList.put("eleven", vList.get("ELEVEN").toString());
			sList.put("twelve", vList.get("TWELVE").toString());
			sList.put("summation", vList.get("SUMMATION").toString());
			statList.add(sList);
			if (isChild){
				if (subject.getList() != null && subject.getList().size() > 0){
					this.getObjectStatChild(statList, subject.getList(), year, num + 1);
				}
			}
		}
	}
	
	/**
	 * 修改状态
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateEnabledObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(idList);
		boolean isEnabled = (Boolean) objectMap.get("isenabled");
		if (isEnabled){
			objectDao.executeHql("update z_major t set t.statuscode = 'b_lxztqy', t.statusname = '启用', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
			this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + " 修改“启用” " + ids, employee, z_majorServiceImpl.class);
		}else{
			objectDao.executeHql("update z_major t set t.statuscode = 'b_lxztty', t.statusname = '停用', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
			this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + " 修改“停用” " + ids, employee, z_majorServiceImpl.class);
		}
		EhcacheUtil.getInstance().remove(Config.MAJORMAP + employee.getCompanyid());
	}
	
	/**
	 * 公开栏目
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateGklmObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String status = objectMap.get("status").toString();
		objectDao.executeHql("update z_major t set t.column1 = '"+ status +"' where t.id in (" + ids + ")");
		EhcacheUtil.getInstance().remove(Config.MAJORMAP + employee.getCompanyid());
	}
	
	/**
	 * 栏目文章关联查询
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public ParametersUtil getObjectRelateArticleNum(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if (objectMap.get("id") == null || objectMap.get("id").toString().equals(""))
			throw new BusinessException(depict + "未找到相应的栏目ID!");
		String id = objectMap.get("id").toString();
		ParametersUtil util = new ParametersUtil();
		String sql = "select distinct a.id from B_article a " +
				" where a.deleted = '0' and a.companyid = ? and a.subjectid = ? ";
		List<Object> valueList = objectDao.queryBySql(sql, employee.getCompanyid(), id);
		util.addSendObject("article", valueList.size());
		sql = "select distinct a.id from B_article a, B_articlerelate r " +
				" where a.id = r.articleid and a.deleted = '0' " + 
				" and a.companyid = ? and r.joinid = ? and r.jointype = ? ";
		valueList = objectDao.queryBySql(sql, employee.getCompanyid(), id, B_articlerelateServiceImpl.wzgllm1);
		util.addSendObject("relate", valueList.size());
		return util;
	}
	
	/**
	 * 栏目文章及关联文章迁移
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateObjectMoveRelateArticle(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if (objectMap.get("oid") == null || objectMap.get("oid").toString().equals(""))
			throw new BusinessException(depict + "未找到迁移的栏目ID!");
		if (objectMap.get("nid") == null || objectMap.get("nid").toString().equals(""))
			throw new BusinessException(depict + "未找到目标的栏目ID!");
		if (objectMap.get("ntxt") == null || objectMap.get("ntxt").toString().equals(""))
			throw new BusinessException(depict + "未找到目标的栏目名称!");
		String sql = "update B_article t set t.subjectid = ?, t.subjectname = ? where t.subjectid = ?";
		objectDao.executeSql(sql, objectMap.get("nid"), objectMap.get("ntxt"), objectMap.get("oid"));
		sql = "update B_articlerelate t set t.joinid = ? where t.joinid = ? and t.jointype = ? ";
		objectDao.executeSql(sql, objectMap.get("nid"), objectMap.get("oid"), B_articlerelateServiceImpl.wzgllm1);
	}
	
	/**
	 * Excel导出
	 */
	public Map<String, String> download(ParametersUtil parameters, A_Employee employee, String rootPath, String httpRootPath) throws Exception {
		Gson gs = new Gson();
		List<Object> subList = this.getDownloadData(parameters,employee);
		String path = "uploadfiles/temp/"+UUID.randomUUID().toString().trim().replaceAll("-", "")+".xls";
		String url = rootPath+path;
		String httpUrl = httpRootPath+path;
		this.createExcel(subList, url);
		Map<String, String> map = new HashMap<String, String>();
		map.put("httpUrl", httpUrl);
		return map;
	}
	
	/**
	 * 生成Excel文件
	 * @param list
	 * @param url
	 * @param sheetName
	 * @throws Exception
	 */
	public void createExcel(List<Object> subList, String url) throws Exception{
		WritableWorkbook book = Workbook.createWorkbook(new File(url)); //创建可写入的 Excel 工作薄
		WritableCellFormat format = new WritableCellFormat();
		WritableFont font = new WritableFont(WritableFont.ARIAL,16,WritableFont.BOLD); //字形
		format.setFont(font);
		format.setAlignment(Alignment.CENTRE);
		format.setVerticalAlignment(VerticalAlignment.CENTRE);
		format.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);  //边框
		
		WritableCellFormat cellformat = new WritableCellFormat();
		cellformat.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
		cellformat.setWrap(true);  //设置单元格自适应列宽
		
		WritableCellFormat headerformat = new WritableCellFormat();
		WritableFont hFont = new WritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD); //字形加粗
		headerformat.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
		headerformat.setFont(hFont);
		
		WritableSheet sheet = book.createSheet("发布统计（按栏目）", 0);

		sheet.mergeCells(0,0,14,0); //a:最左上的列，b最左上的行，c最右下的列，d最右下的行 （合并单元格）
		sheet.getSettings().setDefaultColumnWidth(15);
		sheet.setColumnView(0,10);  //单独设置列宽 （0代表第几列，10代表宽度）
		sheet.setColumnView(1,40);  //单独设置列宽 （0代表第几列，10代表宽度）
		Label label = new Label(0, 0, "按栏目统计发布数据", format);
		sheet.addCell(label);
		for (int i = 0; i < 15; i++) {
			Label label_tem = null;
			switch (i) {
			case 0:
				label_tem = new Label(i, 1, "",headerformat);
				break;
			case 1:
				label_tem = new Label(i, 1, "名称",headerformat);
				break;
			case 2:
				label_tem = new Label(i, 1, "一月",headerformat);
				break;
			case 3:
				label_tem = new Label(i, 1, "二月",headerformat);
				break;
			case 4:
				label_tem = new Label(i, 1, "三月",headerformat);
				break;
			case 5:
				label_tem = new Label(i, 1, "四月",headerformat);
				break;
			case 6:
				label_tem = new Label(i, 1, "五月",headerformat);
				break;
			case 7:
				label_tem = new Label(i, 1, "六月",headerformat);
				break;
			case 8:
				label_tem = new Label(i, 1, "七月",headerformat);
				break;
			case 9:
				label_tem = new Label(i, 1, "八月",headerformat);
				break;
			case 10:
				label_tem = new Label(i, 1, "九月",headerformat);
				break;
			case 11:
				label_tem = new Label(i, 1, "十月",headerformat);
				break;
			case 12:
				label_tem = new Label(i, 1, "十一月",headerformat);
				break;
			case 13:
				label_tem = new Label(i, 1, "十二月",headerformat);
				break;
			case 14:
				label_tem = new Label(i, 1, "年累计",headerformat);
				break;
			default:
				break;
			}
			sheet.addCell(label_tem);
		}
		for (int j = 0; j < subList.size(); j++){
			sheet.addCell(new Label(0,j+2, j+1+"",cellformat));
			sheet.addCell(new Label(1,j+2, ((Map)subList.get(j)).get("name").toString(),cellformat));
			sheet.addCell(new Label(2,j+2, ((Map)subList.get(j)).get("one").toString(),cellformat));
			sheet.addCell(new Label(3,j+2, ((Map)subList.get(j)).get("two").toString(),cellformat));
			sheet.addCell(new Label(4,j+2, ((Map)subList.get(j)).get("three").toString(),cellformat));
			sheet.addCell(new Label(5,j+2, ((Map)subList.get(j)).get("four").toString(),cellformat));
			sheet.addCell(new Label(6,j+2, ((Map)subList.get(j)).get("five").toString(),cellformat));
			sheet.addCell(new Label(7,j+2, ((Map)subList.get(j)).get("six").toString(),cellformat));
			sheet.addCell(new Label(8,j+2, ((Map)subList.get(j)).get("seven").toString(),cellformat));
			sheet.addCell(new Label(9,j+2, ((Map)subList.get(j)).get("eight").toString(),cellformat));
			sheet.addCell(new Label(10,j+2, ((Map)subList.get(j)).get("nine").toString(),cellformat));
			sheet.addCell(new Label(11,j+2, ((Map)subList.get(j)).get("ten").toString(),cellformat));
			sheet.addCell(new Label(12,j+2, ((Map)subList.get(j)).get("eleven").toString(),cellformat));
			sheet.addCell(new Label(13,j+2, ((Map)subList.get(j)).get("twelve").toString(),cellformat));
			sheet.addCell(new Label(14,j+2, ((Map)subList.get(j)).get("summation").toString(),cellformat));
		}
		book.write();
		book.close();
	}
}
